$(function() {
  var page = 1
  var pageSize = 5
  render()
  function render() {
    $.ajax({
      url: '/category/querySecondCategoryPaging',
      type: 'get',
      data: {
        page: page,
        pageSize: pageSize
      },
      success: function(info) {
        console.log(info)
        $('tbody').html(template('tmp',info))
        $('#paginator').bootstrapPaginator({
          bootstrapMajorVersion: 3,
          currentPage: page,
          totalPages: Math.ceil(info.total/info.size),
          onPageClicked: function(a, b, c, p) {
            page = p
            render()
          }
        })
      }
    })
  }

  $('.addCate').on('click',function() {
    $('#addModal').modal('show')
    $.ajax({
      url:'/category/queryTopCategoryPaging',
      type: 'get',
      data: {
        page: page,
        pageSize: 100
      },
      success: function(info) {
        console.log(info)
        $('.dropdown-menu').html(template('tmp2',info))
      }
    })
  })

  $('.dropdown-menu').on('click','li',function() {
    var txt = $(this).children().html()
    $('.btn-text').html(txt);

    $('[name=categoryId]').val($(this).data('id'))
    $('form')
      .data('bootstrapValidator')
      .updateStatus('categoryId', 'VALID')

  })

  $('#file').fileupload({
    done: function(e, data) {
      console.log(data.result.picAddr);
      $('.img_box img').attr('src',data.result.picAddr);
      $('[name=brandLogo]').val(data.result.picAddr);
      $('form').data('bootstrapValidator').updateStatus('brandLogo','VALID')
    }
  })

  $('form').bootstrapValidator({
    excluded: [],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-thumbs-up',
      invalid: 'glyphicon glyphicon-thumbs-down',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
      brandName: {
        validators: {
          notEmpty: {
            message: '二级分类的名称不能为空'
          }
        }
      },
      categoryId: {
        validators: {
          notEmpty: {
            message: '请选择一个一级分类'
          }
        }
      },
      brandLogo: {
        validators: {
          notEmpty: {
            message: '请上传二级分类的图片'
          }
        }
      }
    }
  })

  $('form').on('success.form.bv',function(e) {
    e.preventDefault()
    $.ajax({
      url:'/category/addSecondCategory',
      type:'post',
      data: $('form').serialize(),
      success:function(info) {
        if(info.success) {
          page = 1
          render()
          $('#addModal').modal('hide')
          $('form').data('bootstrapValidator').resetForm(true)
          $('.btn-text').html('请选择一级分类');
          $('.img_box img').attr('src','images/none.png');
        }
      }

    })
  })
})